<template>
  <div class="admin-container">
    <div class="page-header">
      <h2>商品审核</h2>
    </div>

    <el-card>
      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.title" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="卖家名称">
            <el-input v-model="searchForm.sellerName" placeholder="请输入卖家名称" />
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select v-model="searchForm.category" placeholder="全部分类">
              <el-option label="全部分类" value="" />
              <el-option v-for="category in categories" :key="category.value" :label="category.label" :value="category.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select v-model="searchForm.status" placeholder="全部状态">
              <el-option label="全部状态" value="" />
              <el-option label="待审核" value="pending" />
              <el-option label="审核通过" value="approved" />
              <el-option label="审核拒绝" value="rejected" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 商品列表 -->
      <el-table
        v-loading="isLoading"
        :data="filteredProducts"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="商品ID" width="80" />
        <el-table-column label="商品信息" width="300">
          <template #default="scope">
            <div class="product-info">
              <img :src="scope.row.image" alt="商品图片" class="product-image">
              <div class="product-details">
                <div class="product-title">{{ scope.row.title }}</div>
                <div class="product-category">{{ getCategoryText(scope.row.category) }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            <span class="price">¥{{ scope.row.price.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sellerName" label="卖家" width="120" />
        <el-table-column prop="createdAt" label="发布时间" width="180" />
        <el-table-column prop="status" label="审核状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" text @click="viewProductDetail(scope.row.id)">
              查看
            </el-button>
            <template v-if="scope.row.status === 'pending'">
              <el-button type="success" text @click="approveProduct(scope.row.id)">
                通过
              </el-button>
              <el-button type="danger" text @click="rejectProduct(scope.row.id)">
                拒绝
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedProducts.length > 0">
        <span>已选择 {{ selectedProducts.length }} 项</span>
        <el-button type="success" @click="batchApprove">批量通过</el-button>
        <el-button type="danger" @click="batchReject">批量拒绝</el-button>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 拒绝原因弹窗 -->
    <el-dialog v-model="showRejectDialog" title="拒绝原因" width="400px">
      <el-form-item label="拒绝原因" required>
        <el-input
          v-model="rejectReason"
          type="textarea"
          :rows="4"
          placeholder="请输入拒绝原因"
        ></el-input>
      </el-form-item>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRejectDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmReject">确认拒绝</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useProductStore } from '../../store'

const router = useRouter()
const productStore = useProductStore()
const isLoading = ref(false)
const selectedProducts = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const showRejectDialog = ref(false)
const rejectReason = ref('')
let currentRejectProductId = null

// 搜索表单
const searchForm = reactive({
  title: '',
  sellerName: '',
  category: '',
  status: ''
})

// 商品分类（模拟数据）
const categories = ref([
  { value: 'phone', label: '手机数码' },
  { value: 'computer', label: '电脑办公' },
  { value: 'clothing', label: '服装鞋包' },
  { value: 'books', label: '图书文具' },
  { value: 'sports', label: '运动户外' },
  { value: 'other', label: '其他物品' }
])

// 模拟商品数据
const products = ref([
  {
    id: 101,
    title: '全新 小米13 8+256G 黑色 国行正品',
    image: '/images/phone1.jpg',
    price: 3599,
    description: '全新未拆封，官方正品，支持验货。因更换其他手机，低价转让。',
    category: 'phone',
    sellerId: 2,
    sellerName: 'zhangsan',
    status: 'pending',
    reason: '',
    createdAt: '2023-11-10 09:30:00'
  },
  {
    id: 102,
    title: 'MacBook Pro 2022 14英寸 M2 Pro芯片',
    image: '/images/laptop1.jpg',
    price: 14999,
    description: '购买半年，几乎全新，有发票，保修到2024年6月。',
    category: 'computer',
    sellerId: 3,
    sellerName: 'lisi',
    status: 'approved',
    reason: '',
    createdAt: '2023-11-09 14:20:00'
  },
  {
    id: 103,
    title: 'Nike Air Force 1 空军一号 白色',
    image: '/images/shoes1.jpg',
    price: 799,
    description: '尺码42，仅试穿，正品保证，支持专柜验货。',
    category: 'clothing',
    sellerId: 5,
    sellerName: 'zhaoliu',
    status: 'rejected',
    reason: '商品图片不清晰，请提供更多细节图片',
    createdAt: '2023-11-08 16:45:00'
  },
  {
    id: 104,
    title: '考研英语词汇 乱序版',
    image: '/images/book1.jpg',
    price: 25,
    description: '九成新，无笔记，适合2024年考研使用。',
    category: 'books',
    sellerId: 4,
    sellerName: 'wangwu',
    status: 'pending',
    reason: '',
    createdAt: '2023-11-07 10:15:00'
  },
  {
    id: 105,
    title: '全新 华为 MateBook X Pro 13.9英寸',
    image: '/images/laptop2.jpg',
    price: 8999,
    description: '全新未拆封，有发票，支持专柜验货。',
    category: 'computer',
    sellerId: 2,
    sellerName: 'zhangsan',
    status: 'pending',
    reason: '',
    createdAt: '2023-11-06 09:50:00'
  }
])

onMounted(() => {
  loadProducts()
})

const loadProducts = async () => {
  isLoading.value = true
  
  try {
    // 在实际项目中，这里应该从API获取商品数据
    // await productStore.fetchProductsForAudit()
    
    // 模拟数据加载延迟
    await new Promise(resolve => setTimeout(resolve, 500))
  } catch (error) {
    ElMessage.error('加载商品数据失败，请稍后重试')
    console.error('加载商品数据失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 根据搜索条件过滤商品
const filteredProducts = computed(() => {
  let result = [...products.value]
  
  if (searchForm.title) {
    result = result.filter(product => 
      product.title.toLowerCase().includes(searchForm.title.toLowerCase())
    )
  }
  
  if (searchForm.sellerName) {
    result = result.filter(product => 
      product.sellerName.toLowerCase().includes(searchForm.sellerName.toLowerCase())
    )
  }
  
  if (searchForm.category) {
    result = result.filter(product => product.category === searchForm.category)
  }
  
  if (searchForm.status) {
    result = result.filter(product => product.status === searchForm.status)
  }
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  
  return result.slice(start, end)
})

// 总商品数
const total = computed(() => {
  let result = [...products.value]
  
  if (searchForm.title) {
    result = result.filter(product => 
      product.title.toLowerCase().includes(searchForm.title.toLowerCase())
    )
  }
  
  if (searchForm.sellerName) {
    result = result.filter(product => 
      product.sellerName.toLowerCase().includes(searchForm.sellerName.toLowerCase())
    )
  }
  
  if (searchForm.category) {
    result = result.filter(product => product.category === searchForm.category)
  }
  
  if (searchForm.status) {
    result = result.filter(product => product.status === searchForm.status)
  }
  
  return result.length
})

const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置为第一页
}

const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
}

const handleSelectionChange = (selection) => {
  selectedProducts.value = selection.filter(product => product.status === 'pending')
  
  // 提示用户只能选择待审核的商品
  if (selection.length > selectedProducts.value.length) {
    ElMessage.warning('只能选择待审核状态的商品进行批量操作')
  }
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

const getCategoryText = (category) => {
  const categoryMap = categories.value.reduce((map, cat) => {
    map[cat.value] = cat.label
    return map
  }, {})
  return categoryMap[category] || '未知分类'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '审核通过',
    rejected: '审核拒绝'
  }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return typeMap[status] || 'default'
}

const viewProductDetail = (productId) => {
  // 在实际项目中，这里应该跳转到商品详情页面
  // 或者在弹窗中显示商品详情
  ElMessage.info(`查看商品ID为 ${productId} 的详情`)
}

const approveProduct = async (productId) => {
  try {
    await ElMessageBox.confirm('确定要通过该商品的审核吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    })
    
    // 在实际项目中，这里应该调用API通过审核
    const product = products.value.find(p => p.id === productId)
    if (product) {
      product.status = 'approved'
    }
    
    ElMessage.success('商品审核通过')
  } catch (error) {
    // 用户取消操作，不做任何处理
  }
}

const rejectProduct = (productId) => {
  currentRejectProductId = productId
  rejectReason.value = ''
  showRejectDialog.value = true
}

const confirmReject = async () => {
  if (!rejectReason.value.trim()) {
    ElMessage.warning('请输入拒绝原因')
    return
  }
  
  try {
    // 在实际项目中，这里应该调用API拒绝审核
    const product = products.value.find(p => p.id === currentRejectProductId)
    if (product) {
      product.status = 'rejected'
      product.reason = rejectReason.value.trim()
    }
    
    showRejectDialog.value = false
    ElMessage.success('商品已拒绝')
  } catch (error) {
    ElMessage.error('操作失败，请稍后重试')
    console.error('拒绝商品失败:', error)
  }
}

const batchApprove = async () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要批量通过的商品')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要通过选中的 ${selectedProducts.value.length} 个商品的审核吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    })
    
    // 在实际项目中，这里应该调用API批量通过审核
    const ids = selectedProducts.value.map(product => product.id)
    products.value.forEach(product => {
      if (ids.includes(product.id)) {
        product.status = 'approved'
      }
    })
    
    selectedProducts.value = [] // 清空选中状态
    ElMessage.success(`成功通过 ${ids.length} 个商品的审核`)
  } catch (error) {
    // 用户取消操作，不做任何处理
  }
}

const batchReject = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要批量拒绝的商品')
    return
  }
  
  // 批量拒绝需要统一的拒绝原因
  rejectReason.value = ''
  showRejectDialog.value = true
  currentRejectProductId = null // 表示批量拒绝
}
</script>

<style scoped>
.admin-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  font-size: 24px;
  color: #333;
}

.search-section {
  margin-bottom: 20px;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 15px;
}

.product-details {
  flex: 1;
}

.product-title {
  font-size: 14px;
  margin-bottom: 5px;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-category {
  font-size: 12px;
  color: #999;
}

.price {
  color: #ff4d4f;
  font-weight: bold;
}

.batch-actions {
  margin-top: 20px;
  padding: 15px;
  background: #fafafa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .search-form {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }
  
  .product-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .product-image {
    margin-right: 0;
  }
  
  .batch-actions {
    flex-wrap: wrap;
  }
  
  .pagination-container {
    justify-content: center;
  }
}
</style>